<?php

class Admin extends Controller{

	private $identities=array();

	public $autoRender = false;
	public $layout = "admin";

	private $DIR_USERIMAGES = "resource/image/userimages";
	private $IMAGE_EXTENSIONS = array("jpg", "jpeg", "png", "gif");
	private $IMAGE_SIZES = array(
		"thumb" => array(75,75),
		"normal" => array(200,200),
		"large" => array(400,400)
	);

	public function __construct(){
		if($this->doNotInit){
			return;
		}
		parent::__construct();
		$this->init();

		//load identities
		foreach (file("lib/identities") as $identity){
			list($username,$password) = explode(":", $identity, 2);
			$this->identities[$username] = trim($password);
		}

		// load main menu
		$ini = parse_ini_file("lib/admin_menu.ini");
		$menu = array();
		foreach($ini as $label=>$url){
			$menu[] = array(
				"label" => $label,
				"href" => $url,
				"active" => Controller::is_active($url) ? 1 : 0
			);
		}
		$this->set("menu", $menu);
	}

	public function index(){
		$this->render();
	}

	public function login(){
		$username = $_POST["username"];
		$password = $_POST["password"];

		if(isset($this->identities[$username]) && md5($password) == $this->identities[$username]){
			$_SESSION["user"] = $username;
		}else{
			$this->flashSet(__("Prijava nije uspela.",true), "error");
		}

		redirect("/admin");
	}

	public function logout(){
		unset($_SESSION["user"]);
		redirect("/admin");
	}

	public function userimages(){
		$dir = opendir($this->DIR_USERIMAGES);
		$images = array();
		while($f = readdir($dir)){
			$ext = strtolower(substr($f, strrpos($f, ".")+1));
			if(in_array($ext, $this->IMAGE_EXTENSIONS)){
				$images[] = $f;
			}
		}
		echo json_encode($images);
	}
	public function userimage_show($size,$name){
		$dimensions = $this->IMAGE_SIZES[$size];
		$w = $dimensions[0];
		$h = $dimensions[1];
		error_reporting(E_ALL);
		ini_set("display_errors", "On");
		$img = Image::img_create("{$this->DIR_USERIMAGES}/$name");
		Image::img_resize($img, $w, $h);
		Image::img_throw($img, $name);
	}
	public function userimage_upload(){
		$image = $_FILES["userimage"];
		if(!$image["error"]){

			$ext = strtolower(substr($image["name"], strrpos($image["name"], ".")+1));
			if(in_array($ext, $this->IMAGE_EXTENSIONS)){
				$destination = $this->DIR_USERIMAGES."/".$image["name"];
				if(move_uploaded_file($image["tmp_name"], $destination)){
					__("Slika nije poslata");
				}
			}else{
				echo __("Error", true)."! ".__("Poslati fajl nije validna slika", true);
			}
		}else{
			echo __("Error", true) ."! " . __("Poslati fajl nije validan", true) . ".";
		}
	}
	public function userimage_delete($name){
		$status = 0;
		if(!unlink($this->DIR_USERIMAGES."/$name")){
			$status = 1;
		}
		header("X-Status: $status");
	}

	public function kontakt(){
		$this->layout = "default";

		$name = $_POST["name"];
		$email = $_POST["email"];
		$text = $_POST["message"];
		$captcha = $_POST["captcha"];

		$status = 0;
		$ret = __("Poruka je uspešno prosleđena", true);


		$to = CONTACT_EMAIL;
		$subject = "Kontakt sa sajta: $name";
		$message = "<h1>$name <$email></h1>".nl2br($text);
		$headers = "Content-Type: text/html;charset=utf-8\r\n"
				  ."From: \"$name\"<$email>\r\n";

		if(!$name || !$email || !$text || !$captcha){
			$status = 1;
			$ret = __("Sva polja su obavezna", true);
		}elseif (!is_email($email)){
			$status = 1;
			$ret = __("Uneta e-mail adresa nije validna", true);
		}elseif(strtolower($captcha)!=strtolower($_SESSION["kapca"])){
			$status = 1;
			$ret = __("Uneti sigurnosni tekst nije isti kao na slici", true);
		}elseif(!mail($to, $subject, $message, $headers)){
			$status = 1;
			$ret = __("Poruka nije poslata", true);
		}


		$this->set("data", array(
			"name" => $name,
			"email" => $email,
			"message" => $text,
			"captcha" => $captcha
		));
		$this->set("status_code", $status ? "error" : "ok");
		$this->set("status_message", $ret);
		$this->render("page/kontakt");
	}
	public function kontakt_captcha(){
		$buffer = "qwertyuiopasdfghjklzxcvbnm0123456789";
		$ret = "";
		for($i=0; $i<7; $i++){
			$ret .= substr($buffer, rand(0, strlen($buffer)-1), 1);

		}
		error_reporting(E_ALL);ini_set("display_errors", "On");
		$w = 100; $h = 30;
		$img = imagecreatetruecolor($w,$h);
		$white = imagecolorallocate($img, 255, 255, 255);
		$grey = imagecolorallocate($img, 170, 170, 170);
		imagefilledrectangle($img, 0, 0, $w, $h, $grey);

		$font = "resource/cambriab.ttf";
		$size = 14;
		$bbox = imagettfbbox($size, 0, $font, $ret);

		$x = ($w-$bbox[2]+$bbox[0])/2;
		$y = ($h-$bbox[5]+$bbox[3])/2;

		imagettftext($img, $size, 0, $x, $y, $white, $font, $ret);

		$_SESSION["kapca"] = $ret;
		header("Content-Type: image/png; filename=captcha.png");
		imagepng($img);
	}
}